package com.biboheart.adapter.compiler.lexical;

import com.biboheart.adapter.compiler.enums.CharType;
import com.biboheart.adapter.compiler.enums.TokenType;
import com.biboheart.adapter.compiler.utils.TokenUtils;
import lombok.Getter;

final class TokenBuffer {
    private final StringBuilder buffer = new StringBuilder(); // 缓冲区
    @Getter
    private int start;
    @Getter
    private int end = -1;

    public TokenBuffer (int start) {
        this.start = start;
    }

    public int length() {
        return buffer.length();
    }

    public void push(char ch) {
        if (end == -1) {
            end = start;
        }
        buffer.append(ch);
        end ++;
    }

    public String buffer() {
        return buffer.toString();
    }

    public Object value(TokenType type) {
        /*char[] chars = new char[buffer.length()];
        for (int i = 0; i < buffer.length(); i++) {
            chars[i] = buffer.charAt(i);
        }
        String str = 0 == buffer.length() ? "" : String.valueOf(chars);*/
        String str = buffer.toString();
        Object value;
        if (TokenType.TOKEN_NUMBER.equals(type)) {
            if (str.isEmpty()) {
                value = 0;
            } else if (str.contains(".")) {
                value = Double.valueOf(str);
            } else if (str.length() > 10) {
                value = Long.parseLong(str);
            } else {
                value = Integer.parseInt(str);
            }
        } else if (TokenType.TOKEN_STRING.equals(type) && (CharType.CHAR_DQUOTES.equals(TokenUtils.getCharType(buffer.charAt(0))) || CharType.CHAR_SQUOTES.equals(TokenUtils.getCharType(buffer.charAt(0))))) {
            value = str.substring(1, str.length() - 1);
        } else if (TokenType.TOKEN_VARIABLE.equals(type) && CharType.CHAR_BACKQUOTE.equals(TokenUtils.getCharType(buffer.charAt(0)))) {
            value = str.substring(1, str.length() - 1);
        } else {
            value = str;
        }
        return value;
    }
}
